package com.example.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Random;


@Aspect
@Component
public class OrderAspect {

 
    @Pointcut("execution(* com.example.service.OrderService.*(..))")
    public void orderAllMethods() {} 

    @Pointcut("execution(* com.example.service.OrderService.add(..)) || execution(* com.example.service.OrderService.delete(..))")
    public void orderAddDeleteMethods() {} 


    @Before(value = "orderAllMethods()")
    public void beforeAdvice(JoinPoint joinPoint) {
      
        String methodName = joinPoint.getSignature().getName(); 
        System.out.println("[前置增强] hello, 我是一个前置增强 | 目标方法：" + methodName);
    }


    @After(value = "orderAddDeleteMethods()")
    public void afterAdvice(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("[后置增强] bye, 我是一个后置增强 | 目标方法：" + methodName);
        System.out.println("----------------------------------------");
    }


   
    @AfterReturning(value = "orderAllMethods()", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        // 区分void和非void方法的返回值
        String returnMsg = (result == null) ? "无返回值（void方法）" : "返回值：" + result;
        System.out.println("[返回值增强] 目标方法：" + methodName + " | " + returnMsg);
    }


   
    @Around(value = "orderAllMethods()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
    ）
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed(); // 调用目标方法，获取返回值


        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;
        String methodName = joinPoint.getSignature().getName();
        System.out.println("[环绕增强-计时] 目标方法：" + methodName + " | 执行时间：" + costTime + " 毫秒");

        return result;
    }


    @Before(value = "orderAddDeleteMethods()")
    public void permissionCheckAdvice(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();

        int permission = new Random().nextInt(2); // 0或1

    
        if (permission == 1) {
           
            throw new RuntimeException("[权限校验增强] 目标方法：" + methodName + " | 权限不足！无法执行操作");
        } else {
            System.out.println("[权限校验增强] 目标方法：" + methodName + " | 权限通过，允许执行");
        }
    }
}